package com.powerunion.datacollection.persistence.db.jdbc.operator;

import java.sql.SQLException;
import java.util.*;

import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.AppRuntimeException;
import com.powerunion.datacollection.persistence.db.jdbc.base.AccessMannerFactory;
import com.powerunion.datacollection.persistence.db.jdbc.base.DBAccess;
import com.powerunion.datacollection.persistence.db.jdbc.base.DBAccessException;
import com.powerunion.datacollection.util.DBUtil;
import com.powerunion.util.log.LogHelper;

/**
 * 更新操作类
 * @author qyw
 *
 */
public final class UpdateOperator
    extends BaseOperator {
  private static Logger logger = LogHelper.getInstance().getLogger(UpdateOperator.class);
  private ArrayList batchValues = null;
  private int effectCounts;
  private int[] batchEffectCounts;
  private DBUtil dbUtil = null;
  public UpdateOperator() {
    batchValues = null;
    dbUtil = new DBUtil();
  }

  protected void accessImp() throws DBOperatorException {
    try {
      if (batchValues == null) {
        if (this.getParameters().isEmpty()) {
          if (!this.isUseOnlyConnectionFlag()) {
            effectCounts = DBAccess.update(AccessMannerFactory.getAccessManner(
                this.getSql()), this.dbUtil.getConnection());
          }
          else {
            if (!this.isPresentConnectionUsable()) {
              this.setPresentConnection(this.dbUtil.getConnection());
            }
            effectCounts = DBAccess.updateForOneConnection(AccessMannerFactory.
                getAccessManner(this.
                                getSql()), this.getPresentConnection());
          }
        }
        else {
          if (!this.isUseOnlyConnectionFlag()) {
            effectCounts = DBAccess.update(AccessMannerFactory.getAccessManner(this.
                getSql(),
                this.getParameters()), this.dbUtil.getConnection());
          }
          else {
            if (!this.isPresentConnectionUsable()) {
              this.setPresentConnection(this.dbUtil.getConnection());
            }
            effectCounts = DBAccess.updateForOneConnection(AccessMannerFactory.
                getAccessManner(this.
                                getSql(),
                                this.getParameters()),
                this.getPresentConnection());
          }
        }
      }
      else { //执行批量
        this.batchEffectCounts = DBAccess.updateBatch(AccessMannerFactory.
            getAccessManner(this.getSql(),
                            this.batchValues), this.dbUtil.getConnection());
      }
    }
    catch (SQLException ce) {
      logger.error("数据库连接错误", ce);
      throw new DBOperatorException("数据库连接错误", ce);
    }
    catch (DBAccessException dbe) {
      logger.error("QueryOperator执行查询出错", dbe);
      throw new DBOperatorException("QueryOperator执行查询出错", dbe);
    }
  }

  /**
   * 添加一行sql语句的参数（批处理时候使用）
   *
   * @param sqlParameterSet 整条sql语句参数对象
   */
  public void addBatchParameter(SqlParameterSet sqlParameterSet) {
    if (this.batchValues == null) {
      this.batchValues = new ArrayList();
    }
    this.batchValues.add(sqlParameterSet.getSqlParameterSet());
  }

  /**
   * 获取执行后影响的记录条数,不支持批量更新语句
   *  对于 INSERT、UPDATE 或 DELETE 语句，返回行数;
   * 对于什么都不返回的 SQL 语句，返回 0
   *
   * @return int
   */
  public int getEffectCounts() {
    if (!this.isAccessed()) {
      throw new AppRuntimeException(
          "please run method of access() first!");
    }
    return effectCounts;
  }

  /**
   * an array of update counts containing one element for each command in the batch. The elements of the array
   * are ordered according to the order in which commands were added to the batch.
   *
   * @return int[]
   */
  public int[] getBatchEffectCounts() {
    return batchEffectCounts;
  }

}
